package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.ContentConfig;
import com.example.forum.model.Article;
import com.example.forum.model.User;
import com.example.forum.service.imp.ArticleServiceImp;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("article")
public class ArticleController {
    @Autowired
    private ArticleServiceImp articleServiceImp;
    /**
     * 发布对应板块的论坛
     * @return
     */
    @RequestMapping(value = "/create" ,method = RequestMethod.POST)
    public AppResult create(HttpServletRequest request,
                            @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        //判断用户是否禁言,用户对象从session中进行获取
        HttpSession session = request.getSession(false);

        User user =(User) session.getAttribute(ContentConfig.USER_SESSION);
        if(user.getState() == 1){
            //说明此时用户处于禁言的状态
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //设置传递参数
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setContent(content);
        article.setTitle(title);

        articleServiceImp.create(article);

        return AppResult.success("发表文章成功");
    }

    /**
     * 查询首页或者其他板块的信息
     * @param boardId
     * @return
     */
    @RequestMapping(value = "/getAllByBoardId",method = RequestMethod.GET)
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false) Long boardId){
        //进行首页的查询
        List<Article> articles =null;
        if(boardId == null){
            articles = articleServiceImp.selectAll();
        }else{
            articles = articleServiceImp.selectByBoardId(boardId);
        }

        //进行非空判断
        if(articles == null){
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);
    }

    /**
     * 文章详情页面
     * @param id
     * @return
     */

    @RequestMapping(value = "/details",method = RequestMethod.GET)
    public AppResult<Article> getDetail(HttpServletRequest request ,@RequestParam("id") Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);
        //获取文章的详细信息
        Article articleDetail = articleServiceImp.selectDetailById(id);

        //进行文章的校验
        if(articleDetail == null){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //是否为作者本人判断,这里不需要返回错误情况
        if(user.getId() == articleDetail.getUserId() ){
            articleDetail.setOwn(true);
        }
        return AppResult.success(articleDetail);
    }

    /**
     * 用户进行编辑
     * @param request
     * @param id
     * @param title
     * @param content
     * @return
     */
    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public AppResult modify(HttpServletRequest request ,
                            @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user =(User) session.getAttribute(ContentConfig.USER_SESSION);

        //判断用户是否是禁言状态
        if(user.getState() == 1){
            log.warn("用户已经被禁言，state = " + user.getState());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //判断文章是否存在
        Article article = articleServiceImp.selectById(id);

        if(article == null || article.getDeleteState() == 1 ){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否是作者
        if(article.getUserId() != user.getId()){
            log.warn("此文章你不是作者，无权更改；用户id =" + user.getId() +"文章的作者id =" + article.getUserId());
            return AppResult.fail(ResultCode.FAILED_UNAUTHORIZED);
        }
        //判断文章状态
        if( article.getState() == 1){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用服务层，进行数据的更新
        articleServiceImp.modify(id,title,content);
        log.info("数据更新成功 , 文章id：" + article.getId());

        return AppResult.success();

    }

    @RequestMapping(value = "/thumbsUp",method = RequestMethod.POST)
    public AppResult thumbsUp(@RequestParam("id") Long id){
        //参数的校验
        if(id == null || id <= 0){
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //调用服务层
        articleServiceImp.thumbsUpById(id);

        return AppResult.success();
    }

    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public AppResult deleteById(HttpServletRequest request,
                                @RequestParam("id") @NonNull Long id){
        //首先判断id参数
        if(id <= 0){
            log.warn("参数校验不成功，参数id：" + id);
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //判断用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
             return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //拿到文章对象
        Article article = articleServiceImp.selectById(id);
        //进行文章非空状态等校验
        if(article == null || article.getDeleteState() == 1){
            //说明文章被删除，或者不存在
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState() == 1){
            //说明这里的文章的状态异常
            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //调用服务层的删除方法
        articleServiceImp.deleteById(id);

        return AppResult.success();
    }

    @RequestMapping(value = "/getAllByUserId",method = RequestMethod.GET)

    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @RequestParam(value = "userId",required = false)  Long userId) {



        if(userId == null){
            HttpSession session = request.getSession(false);
            //用户id为空的时候，通过session进行获取
            User user = (User) session.getAttribute(ContentConfig.USER_SESSION);

            userId = user.getId();
        }

        List<Article> lists = articleServiceImp.selectByUserId(userId);

        return AppResult.success(lists);
    }
}
